import { loginApi } from '@/api/user'
import { getToken, setToken, delToken } from '@/utils/storage'
import router from '@/router'
import { Message } from 'element-ui'

export default {
  // 开启命名空间
  namespaced: true,
  state() {
    return {
      token: getToken() || ''
    }
  },
  mutations: {
    setToken(state, token) {
      // 存储token到本地
      setToken(token)
      // 存储token到vuex
      state.token = token
    },
    RemoveToken(state) {
      state.token = null
      delToken()
    }
  },
  actions: {
    async login(ctx, { username, password }) {
      try {
        const res = await loginApi({ username, password })
        ctx.commit('setToken', res.data.token)
        Message.success('登录成功')
        router.replace('/')
      } catch (err) {
        Message.error(err.message)
      }
    },
    logout(ctx) {
      ctx.commit('RemoveToken')
      Message.success('退出成功')
    }
  }
}
